package com.atguigu.flink.chapter06;

import com.atguigu.flink.bean.UserBehavior;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;

/**
 * TODO
 *
 * @author cjp
 * @version 1.0
 * @date 2021/8/10 14:20
 */
public class Flink03_PV {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        // 1.读取数据
        SingleOutputStreamOperator<UserBehavior> userBehaviorDS = env
                .readTextFile("F:\\atguigu\\01_course\\code\\flink210323\\input\\UserBehavior.csv")
                .map(r -> {
                    String[] datas = r.split(",");
                    return new UserBehavior(
                            Long.parseLong(datas[0]),
                            Long.parseLong(datas[1]),
                            Integer.parseInt(datas[2]),
                            datas[3],
                            Long.parseLong(datas[4])
                    );
                });

        // 2.处理数据
        userBehaviorDS
                .flatMap(new FlatMapFunction<UserBehavior, Tuple2<String, Integer>>() {
                    @Override
                    public void flatMap(UserBehavior value, Collector<Tuple2<String, Integer>> out) throws Exception {
                        if ("pv".equals(value.getBehavior())) {
                            out.collect(Tuple2.of("pv", 1));
                        }
                    }
                })
                .keyBy(r -> r.f0)
                .sum(1)
                .print();


        env.execute();
    }
}
